//
//  SSSalaryViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/9/26.
//

import UIKit

import HandyJSON

class SSSalaryViewController: SSBaseViewController {
    
    @IBOutlet weak var infoView: UIView!
    
    @IBOutlet weak var pointLab: UILabel!
    
    @IBOutlet weak var totalSalaryLab: UILabel!
    
    @IBOutlet weak var timeLab: UILabel!
    
    var startTime = ""
    var endTime = ""
    var infoLabs = [UILabel]()
    
    
    
    var salary = SSSalary()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "工资明细"
        rightNav()
        
        let startDate = getCurrentDateToWantDate(year: 0, month: -1, day: 0)
        let endDate = getCurrentDateToWantDate(year: 0, month: 0, day: 0)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let startTime = formatter.string(from: startDate)
        let endTime = formatter.string(from: endDate)
        print("--\(startTime),\(endTime)")
        self.startTime = startTime
        self.endTime = endTime
        
        
        let underlineAttriString = NSAttributedString(string:"选择时间",
                                                  attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
        timeLab.attributedText = underlineAttriString
        timeLab.isUserInteractionEnabled = true
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(tapedTitleLabel(_:)))
        timeLab.addGestureRecognizer(tapGes)
        
        setupUIs()
        refreshTimeLab()
        getRewardRecord()
        
        
       
    }
    
    @IBAction func orderListAction(_ sender: Any) {
        let vc = SSIncomeOrderViewController()
        vc.startTime = self.startTime
        vc.endTime = self.endTime
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @objc private func tapedTitleLabel(_ tapGes : UITapGestureRecognizer) {
        let vc = SSTimeViewController()
        vc.modalPresentationStyle = .overFullScreen
        vc.callback { startTime, endTime in
            print("\(startTime)\n\(endTime)")
            let str = "\(startTime)至\(endTime)"
            let underlineAttriString = NSAttributedString(string:str,
                                                      attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
            self.timeLab.attributedText = underlineAttriString
            self.startTime = startTime
            self.endTime = endTime
            self.getRewardRecord()
        }
        self.present(vc, animated: true)
    
        
    }
    
    func refreshTimeLab() {
        let str = "\(startTime)至\(endTime)"
        let underlineAttriString = NSAttributedString(string:str,
                                                  attributes: [NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue])
        self.timeLab.attributedText = underlineAttriString
    }
    
    func refreshTimeData() {
        let infos = ["\(salary.orderNum)","$\(salary.baseIncome)","$\(salary.subsidyIncome)","$\(salary.rewardIncome)"]
        for (index,item) in infos.enumerated() {
            let lab = infoLabs[index]
            lab.text = item
        }
        pointLab.text = "\(salary.overallScore)"
        self.totalSalaryLab.text = "$\(salary.totalIncome)"
    }
    
    
    func setupUIs() {
        
        
        let titles = ["订单数量","基础收入","补贴收入","奖励收入"]
        let infos = ["\(salary.orderNum)","$\(salary.baseIncome)","$\(salary.subsidyIncome)","$\(salary.rewardIncome)"]
        
        var y:Int = 176
        for (index,item) in titles.enumerated() {
            
            let bgView = UIView(frame: CGRect(x: 0, y: y, width: Int(ScreenWidth) - 20 * 2, height: 52))
            infoView.addSubview(bgView)
            y = y + 52
            
            let titleLab = UILabel(frame: CGRect(x: 24, y: 16, width: 100, height: 20))
            titleLab.text = item
            titleLab.font = UIFont.systemFont(ofSize: 12)
            titleLab.textColor = UIColor(hex: "#14233D",alpha: 0.6)
            bgView.addSubview(titleLab)
            
            
            let infoLab = UILabel(frame: CGRect(x: bgView.frame.width - 100 - 24, y: 16, width: 100, height: 20))
            infoLab.textAlignment = .right
            infoLab.text = infos[index]
            infoLab.font = UIFont.systemFont(ofSize: 12)
            infoLab.textColor = UIColor(hex: "#14233D")
            bgView.addSubview(infoLab)
            infoLabs.append(infoLab)
            
            if(index == titles.count -  1){
//                titleLab.textColor = UIColor(hex: "#14233D")
            }else{
                let line = UIView(frame: CGRect(x: 24, y: infoLab.frame.maxY + 16, width: bgView.frame.width -  20 * 2, height: 0.3))
                line.backgroundColor = UIColor(hex: "#14233D",alpha: 0.3)
                bgView.addSubview(line)
            }
        }
    }
    
    func getRewardRecord() {
        let param = [
            "phoneNo": kUserPhone,
            "beginTime": startTime,
            "endTime": endTime,
            "pageCurrent": "1",
            "pageSize": "100",
        ]as[String:AnyObject]
        SSNetwrokManager.share.request(urlString: APIUrl.share.getEMPIncome_URL,
                                       parameters:param) { result in
            guard let workContent = SSSalary.deserialize(from: result, designatedPath:"data") else {
                return
            }
            self.salary = workContent
            self.refreshTimeData()
            print("")
        }
    }
    

    func rightNav() {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        btn.setTitleColor(UIColor(hex: "2475FF"), for: .normal)
        btn.setTitle("评分规则", for: .normal)
        btn .addTarget(self, action: #selector(rightNavAcion), for: .touchUpInside)
        let rightItem = UIBarButtonItem(customView: btn)
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    @objc func rightNavAcion(){
        let url = "http://www.tenhousecleaning.com/clean-h5/rating-rules"
        let vc = SSWebViewController()
        vc.webUrl = url
        UIViewController.current().navigationController?.pushViewController(vc, animated: true)
    }
    
    
    func getCurrentDateToWantDate(year:Int,month:Int,day:Int)->Date {
        let current = Date()
        let calendar = Calendar(identifier: .gregorian)
        var comps:DateComponents?
        
        comps = calendar.dateComponents([.year,.month,.day], from: current)
        comps?.year = year
        comps?.month = month
        comps?.day = day
        return calendar.date(byAdding: comps!, to: current) ?? Date()
    }
   

}


class SSSalary: HandyJSON {
    
    var baseIncome: Float = 0
    var monthTotalIncome: Float = 0
    var overallScore: Float = 0
    var orderNum: Int = 0
    
    
    var rewardIncome: Float = 0
    var subsidyIncome: Float = 0
    var totalIncome: Float = 0

    required init() {}
}
